package com.websever.Http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 请球对象
 * 该类的每一个实例表示客户端发送过来的一个请球
 * 每个请求由三部分组成：
 * 1：请求行
 * 2：消息头
 * 3：消息正文
 */
public class HttpServletRequest {
    private Socket socket;
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本
    private Map<String,String> headers = new HashMap<>();//消息头
    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //解析请求
        parseRequestLine();
        //解析消息头
        parseHeaders();
        //解析消息正文
        parseContent();
    }

    private void parseRequestLine() throws IOException {
        // 解析请求
        String line = readLine();
        System.out.println("请求行"+line);
        String [] data = line.split("\\s");
        method =data[0];
        uri =data[1];
        protocol =data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    private void parseHeaders() throws IOException {
        //读取消息头
        while (true) {
          String  line = readLine();
            if (line.isEmpty()){//如果读到的是空字符串说明单独读取到了CRLF 读到了结尾
                break;
            }
            //Connection:keep-alive
            System.out.println("消息头:"+line);
            String [] kv = line.split(":\\s");
            headers.put(kv[0],kv[1]);
        }
        System.out.println("headers:"+headers);
    }

    private void parseContent(){}

    private String readLine() throws IOException {
        InputStream inp = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';
        char pre = 'a';
        int d1;
        while ((d1 = inp.read())!=-1){
            cur = (char)d1;
            if (pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }
}
